/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.timer;

import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.diagnostic.Logger;

import java.util.Calendar;
import java.util.Date;

public class TimesheetTimer extends Thread {
    // FIX ROB Push these out into configuration...
    private static final String WEB_PAGE = "http://mpdomp1403/topsites/timesheets/index.shtml";
    private static final int DAY_OF_WEEK = Calendar.FRIDAY;
    private static final int HOUR_TO_TRIGGER = 14;

    private Logger logger = Logger.getInstance(getClass().getName());
    private boolean keepGoing = true;

    public void run() {
        Calendar nextTimesheet = Calendar.getInstance();
        Date now = nextTimesheet.getTime();
        nextTimesheet.set(Calendar.DAY_OF_WEEK, DAY_OF_WEEK);
        nextTimesheet.set(Calendar.HOUR_OF_DAY, HOUR_TO_TRIGGER);
        nextTimesheet.set(Calendar.MINUTE, 0);
        nextTimesheet.set(Calendar.SECOND, 0);
        nextTimesheet.set(Calendar.MILLISECOND, 0);
        if (nextTimesheet.getTime().before(now)) {
            nextTimesheet.add(Calendar.DAY_OF_MONTH, 7);
//              nextTimesheet.add(Calendar.MINUTE, 1);
        }
        while (keepGoing) {
            logger.info("Timesheet due at " + nextTimesheet.getTime());
            long millisecondsToGo = nextTimesheet.getTime().getTime() - System.currentTimeMillis();
            logger.info("millisecondsToGo = " + millisecondsToGo);
            if (millisecondsToGo > 0) {
                try {
                    Thread.sleep(millisecondsToGo);
                } catch (InterruptedException e) {
                }
            }
            if (System.currentTimeMillis() >= nextTimesheet.getTime().getTime()) {
                logger.info("Launching Browser");
                BrowserUtil.launchBrowser(WEB_PAGE);
                nextTimesheet.add(Calendar.DAY_OF_MONTH, 7);
//                nextTimesheet.add(Calendar.MINUTE, 1);
            }
        }
        logger.info("Finished");
    }

    public void stopIt() {
        keepGoing = false;
        interrupt();
    }
}
